package com.kai.mqtt.message.service.impl;

import com.kai.mqtt.message.service.IMessageIdService;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author weijk
 * @since 2024/6/10
 */
@Service
public class MessageIdServiceImpl implements IMessageIdService {

    private static final Integer MIN_MSG_ID = 1;

    private static final Integer MAX_MSG_ID = 65535;

    private static final Map<String, AtomicInteger> MAP = new ConcurrentHashMap<>();

    /**
     * 根据客户端 id 获取消息 id
     *
     * @param clientId 客户端 id
     * @return 消息 id
     */
    @Override
    public Integer get(String clientId) {
        AtomicInteger atomicInteger = MAP.computeIfAbsent(clientId, (key) -> new AtomicInteger(MIN_MSG_ID));
        return atomicInteger.getAndUpdate(operand -> operand >= MAX_MSG_ID ? MIN_MSG_ID : operand + 1);
    }

    /**
     * 根据客户端 id 删除消息 id
     *
     * @param clientId 客户端 id
     */
    @Override
    public void remove(String clientId) {
        MAP.remove(clientId);
    }
}
